package org.jash.sportnews2109.ui

import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.alibaba.android.arouter.facade.annotation.Route
import dagger.hilt.android.AndroidEntryPoint
import org.jash.common.adapter.CommonAdapter
import org.jash.common.mvvm.BaseFragment
import org.jash.sportnews2109.BR
import org.jash.sportnews2109.R
import org.jash.sportnews2109.databinding.FragmentVideoBinding
import org.jash.sportnews2109.entity.Page
import org.jash.sportnews2109.entity.Video
import org.jash.sportnews2109.vm.VideoViewModel
@Route(path = "/news/video")
@AndroidEntryPoint
class VideoFragment : BaseFragment<FragmentVideoBinding, VideoViewModel>() {
    val adapter by lazy { CommonAdapter<Video>(R.layout.video_item, BR.video) }
    var page:Int = 1
    val size:Int = 20
    override fun initView() {
        binding.recycler.adapter = adapter
        binding.refresh.setOnRefreshListener {
            page = 1
            viewModel.loadVideo(page, size)
        }
        binding.refresh.setOnLoadMoreListener {
            viewModel.loadVideo(++page, size)
        }
    }

    override fun initData() {
        viewModel.videoLiveData.observe(this, this::load)
        viewModel.loadVideo(page, size)
        //Fragment 的生命周期
//        lifecycle.addObserver()
        //View 的生命周期
//        viewLifecycleOwner.lifecycle.addObserver()
    }
    fun load(p:Page<Video>) {
        if (page == 1) {
            adapter.clear()
        }
        adapter += p.records
        binding.refresh.closeHeaderOrFooter()
    }

    override fun error(throwable: Throwable) {
        super.error(throwable)
        binding.refresh.closeHeaderOrFooter()
    }
}